package com.oauth.global.server.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import com.oauth.global.client.beans.AppInfoBean;
import com.oauth.global.client.beans.BirthdayClientBean;
import com.oauth.service.application.registry.beans.ApplicationInfoBean;
import com.oauth.service.global.beans.Birthday;
import com.oauth.service.global.beans.Dob;

public class GlobalUtil {

	public static List<AppInfoBean> convertToClientList(
			Collection<ApplicationInfoBean> pInfoBeanList) {
		List<AppInfoBean> imageUrlList = new ArrayList<AppInfoBean>();
		for (ApplicationInfoBean infoBean : pInfoBeanList) {
			imageUrlList.add(convertToClientBean(infoBean));
		}
		return imageUrlList;
	}

	public static AppInfoBean convertToClientBean(ApplicationInfoBean pInfoBean) {
		return new AppInfoBean(pInfoBean.getIconUrl(), pInfoBean.getKey(), pInfoBean.getName());
	}

	public static List<BirthdayClientBean> convertToBirthdayList(List<Birthday> pBirthdayList) {
		List<BirthdayClientBean> list = new ArrayList<BirthdayClientBean>();
		Calendar current = Calendar.getInstance();
		if (pBirthdayList != null) {
			for (Birthday birthday : pBirthdayList) {
				BirthdayClientBean clientBean = new BirthdayClientBean();
				clientBean.setAppIconUrl(birthday.getApplicationIconUrl());
				clientBean.setName(birthday.getDisplayName());
				clientBean.setProfileUrl(birthday.getProfileUrl());
				clientBean.setPictureUrl(birthday.getPictureUrl());

				Calendar birth = getBirthCalendar(birthday.getDob());
				if (birth != null) {
					clientBean.setBirthday(getBirthString(birth));
					clientBean.setToday(current.get(Calendar.DAY_OF_MONTH) == birth
							.get(Calendar.DAY_OF_MONTH)
							&& current.get(Calendar.MONTH) == birth.get(Calendar.MONTH));
					birth.add(Calendar.DAY_OF_MONTH, -1);
					clientBean.setTomorrow(current.get(Calendar.DAY_OF_MONTH) == birth
							.get(Calendar.DAY_OF_MONTH)
							&& current.get(Calendar.MONTH) == birth.get(Calendar.MONTH));

					list.add(clientBean);
				}
			}
		}
		return list;
	}

	private static Calendar getBirthCalendar(Dob dob) {
		if (dob == null) {
			return null;
		}
		if (dob.getYear() == 0) {
			dob.setYear(2000);
		}
		try {
			return new GregorianCalendar(dob.getYear(), dob.getMonth() - 1, dob.getDay());
		} catch (Exception e) {
			return null;
		}
	}

	private static String getBirthString(Calendar birth) {
		return birth.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US) + " "
				+ birth.get(Calendar.DAY_OF_MONTH);
	}

}
